import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { Session } from '@/utils/storage'

import axios from 'axios'
import * as sessionKeys from '@/common/keysManage/sessionKeys'
interface RouteModuleInstance {
  [prop: string]: Array<RouteRecordRaw>
}

// 自动导入路由
let moduleObj: RouteModuleInstance = {}
const routeFiles = import.meta.globEager('./modules/*route.ts')
for (const filePath in routeFiles) {
  const path = filePath.replace(/^\.\/(.*)\.route\.\w+$/, '$1')
  const pathArr = path.split('/')
  const moduleName = pathArr.length ? pathArr[pathArr.length - 1] : ''
  if (moduleName) {
    moduleObj[moduleName] = routeFiles[filePath].default
  }
}

let commonRoutes: Array<RouteRecordRaw> = []

Object.keys(moduleObj).forEach((module) => {
  commonRoutes = commonRoutes.concat(moduleObj[module])
})

const routes: Array<RouteRecordRaw> = [
  { path: '/', redirect: '/home' },
  {
    path: '/home',
    name: 'home',
    meta: {
      title: '首页'
    },
    component: () => import('@/views/home.vue')
  },
  ...commonRoutes,
  {
    path: '/notFind',
    name: 'notFind',
    meta: {
      title: '404'
    },
    component: () => import('@/views/notFind.vue')
  },
  {
    // 没有权限和找不到对应菜单页面
    path: '/:pathMatch(.*)',
    redirect: '/notFind'
  }
]

console.log('routes ===>', routes)

const router = createRouter({ history: createWebHashHistory(), routes })

// 路由拦截
router.beforeEach((to, from, next) => {
  next()
  // 检查版本更新
  // if (from.path !== '/') {
  //   checkAppNewVersion()
  // }
})

// 监听页面打开显示
// document.addEventListener('visibilitychange', function () {
//   if (!document.hidden) {
//     checkAppNewVersion()
//   }
// })

// 检查服务端是否已经更新，如果更新刷新页面
// async function checkAppNewVersion() {
//   const url = `/version.json?t=${Date.now()}`
//   let res = null
//   try {
//     res = await axios.get(url)
//   } catch (err) {
//     console.error('checkAppNewVersion error: ', err)
//   }
//   if (!res) return
//   const version = res.data.version
//   const localVersion = Session.get(sessionKeys.APP_VERSION)
//   if (localVersion && localVersion !== version) {
//     Session.set(sessionKeys.APP_VERSION, version)
//     window.location.reload()
//   }
//   Session.set(sessionKeys.APP_VERSION, version)
// }

// checkAppNewVersion()

export default router
